package io.renren.framework.db.mybatis;

import com.baomidou.mybatisplus.core.assist.ISqlRunner;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlHelper;
import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import org.apache.ibatis.session.SqlSession;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: renren-security
 * @description: 原生SQL执行Toolkit
 * @author: xuefeng.gao
 * @create: 2018-09-14 08:56
 **/
public class NativeSqlRunner implements ISqlRunner {

    private static NativeSqlRunner runner;
    private SqlSession session;

    public static NativeSqlRunner db(SqlSession session){
        if(runner==null||runner.sqlSession()==null){
            runner = new NativeSqlRunner();
            runner.session = session;
        }
        return runner;
    }

    /**
     * <p>
     * 获取Session 默认自动提交
     * <p/>
     */
    private SqlSession sqlSession() {
        return session;
    }

    @Override
    @Deprecated
    public boolean insert(String sql, Object... args) {
        return false;
    }

    @Override
    @Deprecated
    public boolean delete(String sql, Object... args) {
        return false;
    }

    @Override
    @Deprecated
    public boolean update(String sql, Object... args) {
        return false;
    }

    @Override
    public List<Map<String, Object>> selectList(String sql, Object... args) {
        try(SqlSession session = sqlSession()) {
            return session.selectList(SELECT_LIST, sqlMap(sql, args));
        }
    }

    @Override
    public List<Object> selectObjs(String sql, Object... args) {
        try(SqlSession session = sqlSession()) {
            return session.selectList(SELECT_OBJS, sqlMap(sql, args));
        }
    }

    @Override
    public Object selectObj(String sql, Object... args) {
        try(SqlSession session = sqlSession()) {
            return SqlHelper.getObject(selectObjs(sql, args));
        }
    }

    @Override
    public int selectCount(String sql, Object... args) {
        try(SqlSession session = sqlSession()) {
            return SqlHelper.retCount(session.<Integer>selectOne(COUNT, sqlMap(sql, args)));
        }
    }

    @Override
    public Map<String, Object> selectOne(String sql, Object... args) {
        return SqlHelper.getObject(selectList(sql, args));
    }

    @Override
    @Deprecated
    public IPage<Map<String, Object>> selectPage(IPage page, String sql, Object... args) {
        return null;
    }

    /**
     * 获取sqlMap参数
     *
     * @param sql  指定参数的格式: {0}, {1}
     * @param args 仅支持String
     * @return
     */
    private Map<String, String> sqlMap(String sql, Object... args) {
        Map<String, String> sqlMap = new HashMap<>();
        sqlMap.put(SQL, StringUtils.sqlArgsFill(sql, args));
        return sqlMap;
    }
}
